package com.sinszm.web.soap;

import com.sinszm.common.util.CommonUtils;
import com.sinszm.web.annotation.Soap;
import com.sinszm.web.soap.service.SzmSoapService;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

import static com.sinszm.web.soap.Constant.DEFAULT_ROOT_PATH;
import static com.sinszm.web.soap.Constant.SPRING_SERVLET;

/**
 * 标题：Soap WebService服务发布
 * 描述：
 * 类名：SzmSoapConfiguration
 * 时间：2020-6-20 10:03
 *
 * @author chenjianbo
 */
@EnableConfigurationProperties(SzmSoapProperties.class)
public class SzmSoapConfiguration {

    @Soap
    @Configuration
    public static class SzmSoap {

        @Resource
        private SzmSoapProperties szmSoapProperties;

        @Bean(name = SPRING_SERVLET)
        public ServletRegistrationBean<CXFServlet> cxfServlet() {
            String path = szmSoapProperties.getPath();
            if (!CommonUtils.isEmpty(path)) {
                path = path.startsWith("/") ? path : "/" + path;
                path = (path.endsWith("/") || path.endsWith("/*") ?
                        path.substring(0, path.lastIndexOf("/"))
                        : path) + "/*";
            }
            return new ServletRegistrationBean<>(
                    new CXFServlet(),
                    CommonUtils.isEmpty(path) ? DEFAULT_ROOT_PATH : path
            );
        }

        @Bean(name = Bus.DEFAULT_BUS_ID)
        public SpringBus springBus() {
            return new SpringBus();
        }

        @Resource
        private SzmSoapService szmSoapService;

        @Resource(name = Bus.DEFAULT_BUS_ID)
        private SpringBus springBus;

        @Bean
        public EndpointImpl soapEndpoint() {
            EndpointImpl endpoint = new EndpointImpl(springBus, szmSoapService);
            endpoint.publish(Constant.DEFAULT_API_NAME);
            return endpoint;
        }

    }

}
